<template>
  <div class="login-container">
    <div class="center-container">
      <div class="left-box">
        <img src="../../../public/image/logo.png" class="logo-img">
        <div class="left-text">Welcome!</div>
        <div class="left-tip">欢迎登录凯汇云车贷系统</div>
        <div class="left-web">http://www.kaihuiyun.com</div>
      </div>
      <div class="form-content">
        <div class="login-tips-name">登录</div>
        <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" autocomplete="on" label-position="left">
          <div class="form-label">用户组</div>
          <el-form-item prop="client_id" class="form-item">
            <el-input
              ref="client_id"
              v-model="loginForm.client_id"
              class="form-input"
              placeholder="请输入用户组"
              name="client_id"
              tabindex="1"
              autocomplete="on"
            />
          </el-form-item>
          <div class="form-label">用户名</div>
          <el-form-item prop="username" class="form-item">
            <el-input
              ref="username"
              v-model="loginForm.username"
              class="form-input"
              placeholder="请输入用户名"
              name="username"
              type="text"
              tabindex="1"
              autocomplete="on"
            />
          </el-form-item>
          <div class="form-label">密码</div>
          <el-form-item prop="password" class="form-item">
            <el-input
              ref="password"
              v-model="loginForm.password"
              class="form-input"
              :type="passwordType"
              placeholder="请输入密码"
              name="password"
              tabindex="2"
              autocomplete="on"
              @keyup.native="checkCapslock"
              @blur="capsTooltip = false"
              @keyup.enter.native="handleLogin"
            />
          </el-form-item>
          <div class="form-label">验证码</div>
          <el-form-item prop="code" class="form-item">
            <el-input
              ref="code"
              v-model="loginForm.code"
              class="form-input code-form-input"
              placeholder="请输入验证码"
              name="code"
              type="number"
              tabindex="1"
              autocomplete="on"
            />
            <img :src="codeUrl" class="code-img">
          </el-form-item>
          <div class="remember-box">
            <el-checkbox @change="checkChange" v-model="checkPassword">记住密码</el-checkbox>
          </div>
          <el-button :loading="loading" class="login-btn" @click.native.prevent="handleLogin" :style="{backgroundColor: isAllFull?'#2D7AEC':''}">登录</el-button>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import { validUsername } from '@/utils/validate'
import SocialSign from './components/SocialSignin'
export default {
  name: 'Login',
  components: { SocialSign },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error('Please enter the correct user name'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('The password can not be less than 6 digits'))
      } else {
        callback()
      }
    }
    return {
      checkPassword: false,   // 记住密码
      loginForm: {
        username: '',
        password: '',
        client_id: '',
        code: ''
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur' }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }],
        client_id: [{ required: true, trigger: 'blur' }],
        code: [{ required: true, trigger: 'blur' }]
      },
      passwordType: 'password',
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {},
      codeUrl: '',
      uuid: ''
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        const query = route.query
        console.log(query)
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  created() {
    this.getcode()
    this.getPassForm()
    // window.addEventListener('storage', this.afterQRScan)
  },
  computed: {
    isAllFull () {
      return this.loginForm.username !== ''&&this.loginForm.password!==''&&this.loginForm.client_id!==''&&this.loginForm.code!==''
    },
  },
  mounted() {
    if (this.loginForm.username === '') {
      this.$refs.username.focus()
    } else if (this.loginForm.password === '') {
      this.$refs.password.focus()
    }
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  methods: {
    checkChange () {},
    /**
     *    获取图片
     * @author
     * @date 2020-11-05 16:53
     * @param arraryBuffer
     **/
    getcode: async function() {
      const self = this
      self.isShowLogin = false
      self.isShowLoading = true
      const data = await this.$http.get('/auth/captchaImage');
      if (data.code === 200) {
        self.codeUrl = 'data:image/gif;base64,' + data.data.img
        self.uuid = data.data.uuid
      }
    },
    checkCapslock(e) {
      const { key } = e
      this.capsTooltip = key && key.length === 1 && (key >= 'A' && key <= 'Z')
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    /**
     * 记住密码
     * @date 2021-05-18
     */
    rememberPass (formData) {
      const exdate = new Date();
      exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * 30); //保存的天数
      document.cookie = "userName=" + formData.username + ";path=/;expires=" + exdate.toLocaleString()
      document.cookie = "userPwd=" + formData.password + ";path=/;expires=" + exdate.toLocaleString()
      document.cookie = "userCliId=" + formData.client_id + ";path=/;expires=" + exdate.toLocaleString()
    },
    /**
     * 获取登录信息
     * @date 2021-05-18
     */
    getPassForm () {
      if (document.cookie.length > 0) {
        this.checkPassword = true
        let arr = document.cookie.split('; '); //这里显示的格式需要切割一下自己可输出看下
        // console.log(arr)
        for (let i = 0; i < arr.length; i++) {
          let arr2 = arr[i].split('='); //再次切割
          //判断查找相对应的值
          if (arr2[0] === 'userName') {
            this.loginForm.username = arr2[1]; //保存到保存数据的地方
          } else if (arr2[0] === 'userPwd') {
            this.loginForm.password = arr2[1];
          } else if (arr2[0] === 'userCliId') {
            this.loginForm.client_id = arr2[1];
          }
        }
      }
    },
    /**
     * 登录
     * @date 2021-05-18
     */
    async handleLogin() {
      this.$refs.loginForm.validate(async valid => {
        if (valid) {
          this.loading = true;
          const data = await this.$oauth.oauthPost('/oauth/token', this.loginForm);
          this.loading = false;
          if (data.access_token) {
            // 记住密码
            if (this.checkPassword) {
              this.rememberPass(this.loginForm)
            }
            let jwt = require('jsonwebtoken');
            let str = jwt.decode(data.access_token);
            sessionStorage.setItem("appId",str.client_id);
            sessionStorage.setItem("userName",str.username);
            sessionStorage.setItem("tokenTime",str.exp);
            // store.commit('SET_TOKEN', data.access_token)
            await this.$store.dispatch('user/login', data.access_token)
            this.$router.push(this.redirect)
            // this.$store.commit('SET_TOKEN', data.access_token)
            // setToken(data.access_token)
          } else {
            this.$message({
              type: 'error',
              message: data.msg
            })
            this.getcode()
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    }
  }
}
</script>

<style lang="scss" scoped>
$bg:#2d3a4b;
$dark_gray:#889aa4;
$light_gray:#eee;

.login-container {
  min-height: 400px;
  width: 100%;
  height: 100%;
  max-width: 100%;
  min-width: 700px;
  padding: 0;
  margin: 0;
  background: url("../../../public/image/login-bg.png");
  overflow: hidden;
  display: flex;
  .center-container{
    width: 700px;
    min-height: 400px;
    margin: auto;
    background: #14244B;
    position: relative;
    .left-box{
      width: calc(100% - 230px);
      margin-top: 50px;
      height: 400px;
      text-align: center;
      .logo-img{
        height: 60px;
        width: 200px;
        display: inline-block;
      }
      .left-text{
        font-size: 30px;
        color: #ffffff;
        margin: 50px auto 25px;
        font-family: Microsoft YaHei
      }
      .left-tip{
        font-size: 24px;
        color: #ffffff;
        margin: 25px auto;
        font-family: Microsoft YaHei
      }
      .left-web{
        font-size: 12px;
        color: #ffffff;
        margin-top: 150px;
        margin-left: auto;
        margin-right: auto;
        font-family: Microsoft YaHei
      }
    }
    .form-content{
      width: 350px;
      position: absolute;
      top: -48px;
      right: -120px;
      background: white;
      min-height: 400px;
      .login-tips-name{
        font-size: 20px;
        color: #2D7AEC;
        font-weight: 600;
        margin: 30px auto 20px 20px;
      }
      .login-form{
        padding: 0 20px 20px;
        .form-label{
          font-size: 16px;
          color: #808080;
        }
        .form-item{
          width: 100%;
          margin: 10px auto;
          .form-input{
            width: 100%;
          }
          .code-form-input{
            width: 75%;
            border-top-left-radius: 0;
            border-top-right-radius: 0;
          }
          .code-img{
            width: 25%;
            height: inherit;
            float: right;
          }
        }
        .remember-box{
          margin: 20px auto;
        }
        .login-btn{
          width: 100%;
          background:#CCCCCC;
          color: white;
        }
      }
    }
  }
}
</style>
